import router from '@/router'
import { useUserStore } from '@/stores'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'

// const baseURL = 'https://wiki.xinchewhd.com.cn'
const baseURL = 'http://localhost:5173/'

const instance = axios.create({
  baseURL,
  timeout: 100000
})

instance.interceptors.request.use(
  (config) => {
    //   携带token
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.code === 1) {
      return res.data
    }
    //   处理业务失败
    ElMessage({ message: res.data.message || '服务异常', type: 'error' })
    return Promise.reject(res.data)
  },
  (err) => {
    //  处理401错误
    ElMessage({
      message: err.response.data.message || '服务异常',
      type: 'error'
    })
    console.log(err)
    if (err.response?.status === 401) {
      router.push('/login')
    }
    return Promise.reject(err)
  }
)

// request<返回值类型>(url必填的, method可选默认是Get, submitData可选的)
type ApiResponse<T = any> = {
  code: number
  message: string
  data: T
}
const request = <T = any>(
  url: string,
  method: Method = 'GET',
  submitData?: object
) => {
  return instance.request<T, ApiResponse<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}

// token拦截
// 没有登录且不在白名单 就拦截到登录页 /login
const whiteList = ['/login']
router.beforeEach((to) => {
  NProgress.start()
  // 组件外的store要写在路由守卫里面
  const userStore = useUserStore()
  if (!userStore.token && !whiteList.includes(to.path)) return '/login'
  // 代码不走if 往下走就是放行
})

// router.afterEach((to) => {
router.afterEach(() => {
  NProgress.done()
  // console.log(to.meta.title)
})

export default instance
export { baseURL, request }
